package com.zhang.hadoop.spring.checker;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhang yufei
 * @date 2022/6/28 20:56
 **/
public class ValidatorUtil {

    private static Validator validator;

    private static ExecutableValidator executableValidator;

    static {
        validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                //快速失败模式  true表示启用，false表示普通模式
                .failFast(false)
                .buildValidatorFactory()
                .getValidator();
        executableValidator=validator.forExecutables();
    }

    public static void validate(Object value) {
        Set<ConstraintViolation<Object>> validateResult = validator.validate(value);
        if (validateResult != null && validateResult.size() > 0) {
            Iterator<ConstraintViolation<Object>> it = validateResult.iterator();
            if (it.hasNext()) {
                ConstraintViolation<Object> cv = it.next();
                throw new RuntimeException(cv.getMessage());
            }
        }
    }

    public static void validateMethod(Object target, Method method, Object[] params){
        Set<ConstraintViolation<Object>> validateResult = executableValidator.validateParameters(target, method, params);
        if (validateResult != null && validateResult.size() > 0) {
            Iterator<ConstraintViolation<Object>> it = validateResult.iterator();
            if (it.hasNext()) {
                ConstraintViolation<Object> cv = it.next();
                throw new RuntimeException(cv.getMessage());
            }
        }

    }
}
